package avicit.bdp.dds.api.job;

import avicit.bdp.dds.api.service.LoggerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket任务日志服务
 *
 * @author xugb
 * @date 2022/4/6 17:45
 */
@Component
@ServerEndpoint("/api/bdp/dds/websocket/tasklog/{id}")
public class WebSocketTaskLogServer {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketTaskLogServer.class);

    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    private static LoggerService loggerService;

    @Autowired
    public void setLoggerService(LoggerService loggerService) {
        WebSocketTaskLogServer.loggerService = loggerService;
    }

    /**
     * 连接建立成功调用
     *
     * @param session 客户端与socket建立的会话
     * @param id      客户端的流程定义ID
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        String key = id + "-" + session.getId();
        sessionPools.put(key, session);
    }

    /**
     * 关闭连接时调用
     *
     * @param id 客户端的流程定义ID
     */
    @OnClose
    public void onClose(Session session, @PathParam("id") String id) {
        String key = id + "-" + session.getId();
        sessionPools.remove(key);
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        if ("ping".equalsIgnoreCase(message)) {
            sendMessage(session, "pong");
            return;
        }
        //{"type":"all/task","processId":"","taskId":""}
        //all--表示全部日志；task--表示节点日志；
        loggerService.queryProcessLogs(session, message);
    }

    @OnError
    public void onError(Session session, @PathParam("id") String id,Throwable throwable) {
        String key = id + "-" + session.getId();
        sessionPools.remove(key);
    }

    /**
     * 发送消息方法
     *
     * @param session 客户端与socket建立的会话
     * @param message 消息
     * @throws IOException
     */
    public void sendMessage(Session session, String message) {
        try {
            if (session != null && session.isOpen()) {
                session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

    }

    public void sendMessage(String id, String message) throws IOException {
        Enumeration<String> keys = sessionPools.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            if (key.startsWith(id)) {
                Session session = sessionPools.get(key);
                if (session != null && session.isOpen()) {
                    sendMessage(session, message);
                } else {
                    sessionPools.remove(key);
                }
            }
        }
    }

}
